import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon, Button, Modal, message, Popconfirm, Divider, Tag, DatePicker, InputNumber,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import { CSVLink } from 'react-csv';

import styles from './Fran.less';

const FormItem = Form.Item;
const { Option } = Select;


@connect(({ fran, loading }) => ({
  fran,
  franListPagination: fran.franListPagination,
  loading: loading.models.fran,
}))
@Form.create()
export default class Fran extends PureComponent {
  state = {
    modalVisible: false,

    csvData: [['firstname', 'lastname', 'email']],

    headers: [{ label: '序号', key: 'franId' }, { label: '加盟商名称', key: 'franName' }, { label: '加盟商地址', key: 'franAddr' },
    { label: '联系人', key: 'franUser' }, { label: '联系电话', key: 'franPhone' },
    { label: '订单数', key: 'ordersCnt' }, { label: '销售金额', key: 'salesAmt' }, { label: '佣金比例', key: 'commRatio' }
      , { label: '结算金额', key: 'settledAmt' }
      , { label: 'M码', key: 'mCode' }
      , { label: '状态', key: 'franSts' }
      , { label: '关联会员数', key: 'userCnt' }
      , { label: '录入时间', key: 'createTime' }],

    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'fran/fetchFranList',
      payload: { "pageNum": "1", "pageSize": "10" }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };
    dispatch({
      type: 'fran/fetchFranList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'fran/fetchFranList',
      payload: { "pageNum": "1", "pageSize": "10" }
    });
  };

  handleSelectRows = rows => {
    let data = [];
    if (rows && (rows.length > 0)) {
      for (let i = 0; i < rows.length; i++) {
        let oneRow = _.cloneDeep(rows[i]);

        if (oneRow.franSts == "0") {
          oneRow.franSts = '正常'
        }
        if (oneRow.franSts == "1") {
          oneRow.franSts = '冻结'
        }

        data.push(oneRow)
      }
    }

    this.setState({
      selectedRows: rows,
      csvData: data,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;
    const values = {
      pageNum: 1,
      pageSize: this.props.franListPagination ? this.props.franListPagination.pageSize : 10,
      ...this.props.form.getFieldsValue(),
    };

    dispatch({
      type: 'fran/fetchFranList',
      payload: values,
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fran/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="加盟商名称">
              {getFieldDecorator('franName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="联系人">
              {getFieldDecorator('franUser')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="联系电话">
              {getFieldDecorator('franPhone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="M码">
              {getFieldDecorator('mCode')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('franSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">正常</Option>
                  <Option value="1">冻结</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </span>
        </div>
      </Form>
    );
  }

  _changeFranStatus(type) {
    let recordList = [];
    let list = this.state.selectedRows;
    if (list && list.length > 0) {
      for (let i in list) {
        let one = { franId: list[i].franId }
        recordList.push(one)
      }
    }

    this.props.dispatch({
      type: 'fran/changeFranStatus',
      payload: { franSts: type, franList: recordList },
      callback: () => this.handleSearch()
    });
  }

  render() {
    const tableData = {}
    tableData['list'] = this.props.fran.franList;
    tableData['pagination'] = this.props.fran.franListPagination;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'franId',
        key: 'franId',
      },
      {
        title: '加盟商名称',
        dataIndex: 'franName',
        key: 'franName',
      },
      {
        title: '加盟商地址',
        dataIndex: 'franAddr',
        key: 'franAddr',
      },
      {
        title: '联系人',
        dataIndex: 'franUser',
        key: 'franUser',
      },
      {
        title: '联系电话',
        dataIndex: 'franPhone',
        key: 'franPhone',
      },
      {
        title: '订单数',
        dataIndex: 'ordersCnt',
        key: 'ordersCnt',
      },
      {
        title: '销售金额',
        dataIndex: 'salesAmt',
        key: 'salesAmt',
      },
      {
        title: '佣金比例',
        dataIndex: 'commRatio',
        key: 'commRatio',
      },
      {
        title: '结算金额',
        dataIndex: 'settledAmt',
        key: 'settledAmt',
      },
      {
        title: 'M码',
        dataIndex: 'mCode',
        key: 'mCode',
      },
      {
        title: '状态',
        dataIndex: 'franSts',
        key: 'franSts',
        render(val) {
          return val == "0" ? '正常' : val == "1" ? '冻结' : null;
        },
      },
      {
        title: '关联会员数',
        dataIndex: 'userCnt',
        key: 'userCnt',
      },
      {
        title: '录入时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/fran/detail/' + record.franId }))}>查看</a>
            <Divider type="vertical" />
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/fran/editFran/' + record.franId }))}>编辑</a>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderAdvancedForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/fran/editFran/new' }))}>
                添加加盟商
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title={"确定要冻结选中的" + this.state.selectedRows.length + "个加盟商吗?"} placement="bottom" onConfirm={() => this._changeFranStatus(1)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="download" >
                      冻结
                  </Button>
                  </Popconfirm>
                  <Popconfirm title={"确定要解冻选中的" + this.state.selectedRows.length + "个加盟商吗?"} placement="bottom" onConfirm={() => this._changeFranStatus(0)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="upload">
                      解冻
                  </Button>
                  </Popconfirm>
                  <Button type="primary">
                    <CSVLink data={this.state.csvData} headers={this.state.headers} filename={"加盟商.csv"}>导出</CSVLink>
                  </Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={this.props.loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="franId"
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
